package com.bsg.upm.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.http.RespJsonFactory;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		HttpSession session = request.getSession();
		boolean invalid = false;
		UserEntity user = (UserEntity) session.getAttribute("user");
		if (user == null) {
			invalid = true;
		}

		if (invalid) {
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
			PrintWriter out = response.getWriter();
			out.write(JSONObject.toJSONString(RespJsonFactory.build(HttpStatus.SC_UNAUTHORIZED, "未授权登录")));
			out.close();
			return false;
		}
		return true;
	}
}
